package com.wsoft.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wsoft.system.entity.SysMenuResourceRelationEntity;
import com.wsoft.system.entity.SysResourceEntity;
import com.wsoft.system.mapper.SysMenuResourceRelationMapper;
import com.wsoft.system.mapper.SysResourceMapper;
import com.wsoft.system.query.resourse.MenuResourceRelationQuery;
import com.wsoft.system.service.ISysMenuResourceRelationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author juiet
 * @since 2024年11月18日 17:14:28
 */
@Service
public class SysMenuResourceRelationServiceImpl extends ServiceImpl<SysMenuResourceRelationMapper, SysMenuResourceRelationEntity> implements ISysMenuResourceRelationService {

 @Resource
 private SysResourceMapper resourceMapper;
    @Override
    public List<SysResourceEntity> getResourceByMenuIds(List<Long> menuIds) {
        QueryWrapper<SysMenuResourceRelationEntity> query = new QueryWrapper<>();
        query.lambda().in(SysMenuResourceRelationEntity::getMenuId, menuIds);
        List<SysMenuResourceRelationEntity> list = list(query);
        if(CollUtil.isNotEmpty(list)){
            List<Long> resourceIds = list.stream().map(SysMenuResourceRelationEntity::getResourceId).collect(Collectors.toList());
            return resourceMapper.selectBatchIds(resourceIds);
        }
        return new ArrayList<>();
    }

    @Override
    public void insertRelations(MenuResourceRelationQuery query) {
        //清空关系
        deleteByMenuId(query.getMenuId());
        query.getResourceIds().forEach(e->{
            SysMenuResourceRelationEntity entity = new SysMenuResourceRelationEntity();
            entity.setMenuId(query.getMenuId());
            entity.setResourceId(e);
            save(entity);
        });
    }

    @Override
    public List<SysMenuResourceRelationEntity> getRelations(Long menuId) {
        QueryWrapper<SysMenuResourceRelationEntity> query = new QueryWrapper<>();
        query.lambda().eq(SysMenuResourceRelationEntity::getMenuId,menuId);
        return list(query);
    }

    private void deleteByMenuId(Long menuId){
        QueryWrapper<SysMenuResourceRelationEntity> query = new QueryWrapper<>();
        query.lambda().eq(SysMenuResourceRelationEntity::getMenuId,menuId);
        remove(query);
    }
}
